#include <graphics.h>
#include "settings.h"
#include "snake.h"
#include "food.h"
#include <stdio.h>

bool run_game(void);
void init_snake(Snake &);
Snake snake(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, UP);
Food food(0, 0);

int main(void)
{
	initgraph(SCREEN_WIDTH, SCREEN_HEIGHT);
	setcaption("snake by YbJerry");
	randomize();
	init_snake(snake);
	food.create_food(snake);
	run_game();
	return 0;
}

bool run_game(void)
{
	key_t key_now = UP;
	while (!snake.check_collision())
	{
		int i=0;
		if (keystate(VK_UP))
		{
			if(snake.move(UP))
				key_now = UP;
			else
				snake.move(key_now);
		}
		else if (keystate(VK_DOWN))
		{
			if(snake.move(DOWN))
				key_now = DOWN;
			else
				snake.move(key_now);
		}
		else if (keystate(VK_LEFT))
		{
			if(snake.move(LEFT))
				key_now = LEFT;
			else
				snake.move(key_now);
		}
		else if (keystate(VK_RIGHT))
		{
			if(snake.move(RIGHT))
				key_now = RIGHT;
			else
				snake.move(key_now);
		}
		else
			snake.move(key_now);
		snake.check_collision(food);
		flushkey();
		cleardevice();
		snake.draw();
		food.draw();
		delay_ms(RETIME);
	}
	setcolor(DARKGRAY);
	setfont(-FONT_SIZE, FONT_PROPORTTION, "Consolas");
	settextjustify(CENTER_TEXT, CENTER_TEXT);
	outtextxy(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, "Game Over");
	getch();
	return 0;
}

void init_snake(Snake &snake)
{
	for (int i = 0; i < INIT_BODY; ++i)
		snake.add();
}